package com.jun.basic.filter;

import com.jun.basic.domain.User;
import com.jun.basic.service.impl.UserServiceImpl;
import com.jun.basic.utils.JsonData;
import com.jun.basic.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

@Slf4j
@WebFilter(urlPatterns = "/api/v1/pri/*", filterName = "loginFilter")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("doFilter");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 先从请求头中进行获取，再从参数中进行获取
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            token = request.getParameter("token");
        }
        // 存在token
        if (!StringUtils.isEmpty(token)) {
            // 为了验证这里，需要先进行登陆，然后使用登陆之后的token获取user
            User user = UserServiceImpl.sessionMap.get(token);
            if (Objects.nonNull(user)) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                renderJson(response, JsonUtils.toJsonString(JsonData.buildFail(-2, "登陆失败，没有登陆过")));
            }
        } else {
            renderJson(response, JsonUtils.toJsonString(JsonData.buildFail(-3, "登陆失败,无token")));
        }

    }

    /**
     * 输出流输出
     */
    private void renderJson(HttpServletResponse response, String json) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        try (PrintWriter writer = response.getWriter()) {
            writer.println(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
